<?php
namespace App\Http\Controllers\Client\Shop\Explore;

use App\Http\Controllers\ClientController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ExploreListBeforeController extends ClientController
{

    /**
     * 接受任务前检查接单条件
     */
    public function index()
    {

        try{
            $notice = $this->userInfo['notice'] && true;
            $result = ['notice'=>$notice];

            // 查询我的达人信息
            $talent_message = DB::table('talent')->where('we_id','=',$this->we_id)->first();
            $talent_message = json_decode(json_encode($talent_message), true);

            if(!$talent_message){
                return $this->setReturnJson(1,'您未绑定达人信息，请在“我的”页面绑定账号',$result);
            }
            if($talent_message['status'] !== 1){
                return $this->setReturnJson(1,'您的账号未通过认证，无法接单',$result);
            }

            // 查询当前openid接单当前的接单次数
            $count = DB::table('explore_work')
                ->where('receiver_we_id','=',$this->we_id)
                ->where('created_at' ,'>',date('Y-m-d 00:00:00'))
                ->count();
            if ($count >= 3 && env("APP_ENV") === "production") {
                return $this->setReturnJson(1,'每日限接3单，您已超出接单上限，请明天再来。',$result);
            }


            // 查询当前账号今天接的第一单的地区，只能在此地区接单
            $order = DB::table('explore_work as ew')
                ->leftJoin('shop','ew.shop_id','=','shop.shop_id')
                ->leftJoin('dict_area as da','shop.city','=','da.id')
                ->where('ew.receiver_we_id','=',$this->we_id)
                ->where('ew.created_at' ,'>',date('Y-m-d 00:00:00'))
                ->select('da.id','da.short_name','da.path')
                ->first();
            $order = json_decode(json_encode($order), true);

            if($order){
                return $this->setReturnJson(0,'您今日已接【'.$order['short_name'].'】的订单，不能再接其他地区的订单',[
                    'order'=>true,
                    'order_city'=>$order['id'],
                    'order_city_name'=>$order['short_name'],
                    'notice'=>$notice,
                ]);
            }

            if(!$talent_message['intelligent']){
                return $this->setReturnJson(2,'您当前的账号是普通用户，暂时不能接点评补发订单，只能接霸王餐订单。如需升级为达人用户，请联系在线客服。',$result);
            }

            return $this->setReturnJson(0,'',$result);
        } catch (\Exception $e) {
            Log::error(ExploreListBeforeController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '信息查询失败');
        }

    }

}
